﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Transactions;

public partial class Main_ServiceInvoice_TransactionFormat_PurchaseOrder : System.Web.UI.Page
{
    string strsql = string.Empty;
    Datautility DU = new Datautility();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            if (Request.QueryString["action"] != null)
            {
                if (Request.QueryString["action"].ToString() == "addnew")
                {

                    PnlAddNew.Visible = true;
                    _BindDdlAdditionTax();

                }
                else if (Request.QueryString["action"].ToString() == "view")
                {
                    PnlView.Visible = true;
                    _BindGridViewData("0");
                    if (Request.QueryString["msg"] != null)
                    {
                        if (Request.QueryString["msg"].ToString() == "true")
                        {
                            lblMsg.Attributes.Add("class", "true");
                            lblMsg.Text = "Purchase Order Format Created Successfully..";
                            lblMsg.Focus();
                        }
                        else if (Request.QueryString["msg"].ToString() == "Update")
                        {
                            lblMsg.Attributes.Add("class", "true");
                            lblMsg.Text = "Purchase Order Format Updated Successfully..";
                            lblMsg.Focus();
                        }
                    }
                    else
                    {
                        lblMsg.Text = "";
                    }
                }
                else if (Request.QueryString["action"].ToString() == "Edit")
                {

                    if (Request.QueryString["FormatId"] != null)
                    {
                        if (Request.QueryString["Status"].ToString() == "Edit")
                        {
                            PnlAddNew.Visible = true;
                            _BindDdlAdditionTax();
                            _BindEditTranFormat_Main(Request.QueryString["FormatId"].ToString());
                            hidFormatId.Value = Request.QueryString["FormatId"].ToString();
                            btnSave.Text = "Update";
                        }
                    }
                }
            }
        }
    }
    private void _BindDdlAdditionTax()
    {
        DataTable DT = DU.getdatausingprocedure("USP_IVC_GetAdditionalTax");
        ddlAdditionalTax.DataSource = DT;
        ddlAdditionalTax.DataTextField = "MAINCLASSNAME";
        ddlAdditionalTax.DataValueField = "Mainclassid";
        ddlAdditionalTax.DataBind();
        ddlAdditionalTax.Items.Insert(0, new ListItem("", "0"));

    }
    private void _SavePurchaseOrder_Main(string strFormatId)
    {
        try
        {
            if (strFormatId != string.Empty)
            {
                if (_CheckDuplicateFormatName(strFormatId))
                {
                    SqlParameter[] sparam ={
                                       new SqlParameter("@FormatId",strFormatId),
                                       new SqlParameter("@FormatName",txtFormatName.Text),
                                       new SqlParameter("@SetDefault",chkDefualt.Checked),
                                       new SqlParameter("@Description",chkDescriptions.Checked),
                                       new SqlParameter("@UOM",chkUOM.Checked),
                                       new SqlParameter("@PreparedBy",chkPreparedBy.Checked),
                                       new SqlParameter("@CheckedBY",chkCheckedBy.Checked),
                                       new SqlParameter("@Narration",chkNarration.Checked),
                                       new SqlParameter("@Remarks",chkRemarks.Checked),
                                       new SqlParameter("@CName",Session["userid"].ToString())
                                   };
                    string strCurrentId = DU.ExecuteProcedure_Scope_Identity("USP_IVC_SavePurchaseOrderFormat", sparam);
                    if (strCurrentId != string.Empty)
                    {
                        _SavePurchaseOrder_Numbers(strCurrentId);
                        _SavePurchaseOrder_Tax_Discount(strCurrentId);

                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
    private void _SavePurchaseOrder_Numbers(string strFormatId)
    {
        try
        {

            if (strFormatId != string.Empty)
            {
                SqlParameter[] sparam ={
                                       new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString()),
                                       new SqlParameter("@FORMATID",strFormatId),
                                       new SqlParameter("@NUMBERINGMETHOD",ddlType.SelectedValue),
                                       new SqlParameter("@PREFIX",txtPrefix.Text),
                                       new SqlParameter("@STARTNUMBER",txtStartNo.Text),
                                       new SqlParameter("@SUFFIX",txtSuffix.Text.Trim()),
                                       new SqlParameter("@NUMWIDTH",txtWidthofNo.Text),
                                       new SqlParameter("@PREFILLZERO","0"),
                                       new SqlParameter("@RESETYEAR",chkResetYear.Checked)
                                   };
                int result = DU.executeprocedure("USP_IVC_SavePurchaseOrderFormat_Numbers", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void _SavePurchaseOrder_Tax_Discount(string strFormatId)
    {
        try
        {

            if (strFormatId != string.Empty)
            {
                SqlParameter[] sparam ={
                                       new SqlParameter("@FORMATID",strFormatId),
                                       new SqlParameter("@TAXLEVEL",rbtApplyTax.SelectedValue),
                                       new SqlParameter("@DISCOUNTLEVEL",rbtApplyDiscount.SelectedValue),
                                       new SqlParameter("@TAXTYPEID",ddlAdditionalTax.SelectedValue),
                                       new SqlParameter("@TAXCALON","0"),
                                       new SqlParameter("@ITEMTAXTYPE",rbtServiceTaxSettings.SelectedValue)
                                   };
                int result = DU.executeprocedure("USP_IVC_SavePurchaseOrderFormat_Tax_Discount_Details", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                _SavePurchaseOrder_Main(hidFormatId.Value);
                scope.Complete();
            }

            if (btnSave.Text == "Save")
            {
                Response.Redirect("PurchaseOrder.aspx?action=view&msg=true");
            }

            if (btnSave.Text == "Update")
            {
                Response.Redirect("PurchaseOrder.aspx?action=view&msg=Update");
            }

        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        if (btnSave.Text == "Update")
        {
            Response.Redirect("PurchaseOrder.aspx?action=view");
        }
        else
        {
            Response.Redirect("TransactionFormat.aspx");
        }

    }
    private bool _CheckDuplicateFormatName(string strFormatId)
    {
        bool flag;
        strsql = "Select FormatName from IVC_PurchaseOrderFormat where FormatId<>'" + strFormatId + "' and FormatName='" + txtFormatName.Text.Trim() + "'";
        DataTable DT = DU.getdata(strsql);
        if (DT.Rows.Count > 0)
        {
            flag = false;
            lblMsg.Text = "Duplicate Format Name";
        }
        else
        {
            flag = true;
            lblMsg.Text = "";
        }
        return flag;
    }
    private void _ResetControl(Control Ctrl)
    {
        foreach (Control c in Ctrl.Controls)
        {
            if (c.GetType() == typeof(TextBox))
            {
                ((TextBox)(c)).Text = string.Empty;
            }
            if (c.GetType() == typeof(CheckBox))
            {
                ((CheckBox)(c)).Checked = false;
            }
            if (c.GetType() == typeof(DropDownList))
            {
                ((DropDownList)(c)).SelectedIndex = 0;
            }
            if (c.GetType() == typeof(RadioButtonList))
            {
                ((RadioButtonList)(c)).SelectedIndex = 0;
            }
            if (c.GetType() == typeof(HiddenField))
            {
                ((HiddenField)(c)).Value = "0";
            }
            if (c.HasControls())
            {
                _ResetControl(c);
            }
        }
    }

    private void _BindEditTranFormat_Main(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            SqlParameter[] sparam ={
                                       new SqlParameter("@FORMATID",strFormatId)
                                   };
            DataTable DTFormatMain = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormat", sparam);
            if (DTFormatMain.Rows.Count > 0)
            {
                txtFormatName.Text = DTFormatMain.Rows[0]["FORMATNAME"].ToString();
                chkDefualt.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["SETDEFAULT"].ToString());
                chkDescriptions.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["Description"].ToString());
                chkPreparedBy.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["PREPAREDBY"].ToString());
                chkUOM.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["UOM"].ToString());
                chkRemarks.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["REMARKS"].ToString());
                chkNarration.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["NARRATION"].ToString());
                chkCheckedBy.Checked = Convert.ToBoolean(DTFormatMain.Rows[0]["CHECKEDBY"].ToString());
                _BindEditTranFormat_Numbers(strFormatId);
                _BindEditTranFormat_TaxDiscounts(strFormatId);

            }
        }
    }

    private void _BindEditTranFormat_TaxDiscounts(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            SqlParameter[] sparam ={
                                       new SqlParameter("@FORMATID",strFormatId)
                                   };
            DataTable DTFormatMain = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormatSettings", sparam);
            if (DTFormatMain.Rows.Count > 0)
            {
                rbtApplyDiscount.SelectedValue = DTFormatMain.Rows[0]["DiscountLevel"].ToString();
                rbtApplyTax.SelectedValue = DTFormatMain.Rows[0]["TaxLevel"].ToString();
                ddlAdditionalTax.SelectedValue = DTFormatMain.Rows[0]["TaxTypeId"].ToString();
                if (DTFormatMain.Rows[0]["TaxLevel"].ToString() == "True")
                {
                    rbtApplyTax.Items[1].Selected = true;
                    panelServiceTax.Visible = true;
                    panelServiceTax.Style.Add("display", "inline");
                    panelAdditionalTax.Style.Add("display", "none");
                    rbtServiceTaxSettings.SelectedValue = DTFormatMain.Rows[0]["ItemTaxType"].ToString();
                }
            }
        }
    }

    private void _BindEditTranFormat_Numbers(string strFormatId)
    {
        if (strFormatId != string.Empty)
        {
            SqlParameter[] sparam ={
                                        new SqlParameter("@FORMATID",strFormatId),
                                        new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString())
                                   };
            DataTable DTFormatNumber = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormat_Numbers", sparam);
            if (DTFormatNumber.Rows.Count > 0)
            {
                txtPrefix.Text = DTFormatNumber.Rows[0]["PREFIX"].ToString();
                txtStartNo.Text = DTFormatNumber.Rows[0]["STARTNUMBER"].ToString();
                txtSuffix.Text = DTFormatNumber.Rows[0]["SUFFIX"].ToString();
                txtWidthofNo.Text = DTFormatNumber.Rows[0]["NUMWIDTH"].ToString();
                chkResetYear.Checked = Convert.ToBoolean(DTFormatNumber.Rows[0]["RESETYEAR"].ToString());
                ddlType.SelectedValue = DTFormatNumber.Rows[0]["NUMBERINGMETHOD"].ToString();

            }
        }
    }

    private void _BindGridViewData(string strFormatId)
    {
        SqlParameter[] sparam ={
                                       new SqlParameter("@FormatId",strFormatId)
                                   };
        DataTable DTFormatMain = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormat", sparam);
        grdDisplay.DataSource = DTFormatMain;
        grdDisplay.DataBind();
    }
    protected void grdDisplay_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (Convert.ToBoolean(e.Row.Cells[2].Text) == true)
            {
                e.Row.Cells[2].Text = "Yes";
            }
            else
            {
                e.Row.Cells[2].Text = "No";
            }
            if (Convert.ToBoolean(e.Row.Cells[3].Text) == true)
            {
                e.Row.Cells[3].Text = "Yes";
            }
            else
            {
                e.Row.Cells[3].Text = "No";
            }

            if (Convert.ToBoolean(e.Row.Cells[4].Text) == true)
            {
                e.Row.Cells[4].Text = "Yes";
            }
            else
            {
                e.Row.Cells[4].Text = "No";
            }

            if (Convert.ToBoolean(e.Row.Cells[5].Text) == true)
            {
                e.Row.Cells[5].Text = "Yes";
            }
            else
            {
                e.Row.Cells[5].Text = "No";
            }

            if (Convert.ToBoolean(e.Row.Cells[6].Text) == true)
            {
                e.Row.Cells[6].Text = "Yes";
            }
            else
            {
                e.Row.Cells[6].Text = "No";
            }

            if (Convert.ToBoolean(e.Row.Cells[7].Text) == true)
            {
                e.Row.Cells[7].Text = "Yes";
            }
            else
            {
                e.Row.Cells[7].Text = "No";
            }

            if (Convert.ToBoolean(e.Row.Cells[8].Text) == true)
            {
                e.Row.Cells[8].Text = "Yes";
            }
            else
            {
                e.Row.Cells[8].Text = "No";
            }
        }
    }

    protected void grdDidplay_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        string strDataKey = grdDisplay.SelectedDataKey.Value.ToString();
        Response.Redirect("PurchaseOrder.aspx?Status=Edit&action=Edit&FormatId=" + strDataKey);
    }
}
